package main

import (
	"database/sql"
	_"github.com/go-sql-driver/mysql"
	//"time"
)

const LOG_STATUS_SUCC = 1
const LOG_STATUS_FAIL = 2

//获取可调度任务
func getTaskList() (map[int]map[string]string) {
	query_sql := "select * from rabbitmq_account_config where status = 1"
	ret := queryMultiple(query_sql,1)
	return ret
}


func queryMultiple(query_sql string, args... interface{}) (map[int]map[string]string) {
	//查询数据库
	db := connect()
	rows, err := db.Query(query_sql, args...)
	defer db.Close()
	if (err != nil) {
		panic(err.Error())
	}

	//构造scanArgs、values两个数组，scanArgs的每个值指向values相应值的地址
	columns, _ := rows.Columns()
	scanArgs := make([]interface{}, len(columns))
	values := make([][]byte, len(columns))
	for i := range values {
		scanArgs[i] = &values[i]
	}

	//最后得到的map
	i := 0
	ret := make(map[int]map[string]string)
	for rows.Next() {
		err = rows.Scan(scanArgs...);
		record := make(map[string]string) //每行数据
		for k, v := range values { //每行数据是放在values里面，现在把它挪到row里
			record[columns[k]] = string(v)
		}
		ret[i] = record //装入结果集中
		i++
	}

	return ret
}

func querySingle(query_sql string, args... interface{}) (map[string]string) {
	//查询数据库
	db := connect()
	rows, err := db.Query(query_sql, args...)
	defer db.Close()
	if (err != nil) {
		panic(err.Error())
	}

	//构造scanArgs、values两个数组，scanArgs的每个值指向values相应值的地址
	columns, _ := rows.Columns()
	scanArgs := make([]interface{}, len(columns))
	values := make([][]byte, len(columns))
	for i := range values {
		scanArgs[i] = &values[i]
	}
	rows.Next()
	err = rows.Scan(scanArgs...);
	record := make(map[string]string) //每行数据
	for k, v := range values { //每行数据是放在values里面，现在把它挪到row里
		record[columns[k]] = string(v)
	}

	return record
}

func insert(insert_sql string, args... interface{}) int64{
	db := connect()
	res, err := db.Exec(insert_sql, args...)
	defer db.Close()
	if (err != nil) {
		panic(err.Error())
	}
	id, _ := res.LastInsertId()
	return id
}

func update(update_sql string, args... interface{}) bool{
	db := connect()
	_, err := db.Exec(update_sql, args...)
	defer db.Close()
	if (err != nil) {
		panic(err.Error())
	}
	return true
}


func connect() (*sql.DB) {
	config := GetConfig()
	dsn := config.Mysql.Username + ":" + config.Mysql.Password + "@tcp(" + config.Mysql.Host + ")/" + config.Mysql.Dbname + "?charset=" + config.Mysql.Charset
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		panic(err.Error())
	}
	return db
}


